package com.gta.edu.sdk.common.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class ValidateLoginFilter implements Filter {
	private static final Logger LOG = LogManager.getLogger(ValidateLoginFilter.class);
	private String[] unFilterURLs = {"/login/*","/user-login-sys/*","/commons/jsp/error/*","/index.jsp","/serviceprovider/*"};

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hreq = (HttpServletRequest) req;
		String url = hreq.getRequestURI();
		HttpServletResponse hres = (HttpServletResponse) res;
		if (url.contains(".")){
			chain.doFilter(req, res);
			return;
		}
		if(url.equals(hreq.getContextPath()+"/")){
			chain.doFilter(req, res);
			return;
		}
		
		// 过滤掉jsp页面中加入的文件公共路径
//		if (url.contains(".jsp")) {
//			url = url.replace("/frame-base/WEB-INF/jsp", "");
//		}
		// 如果是在配置中不需要拦截的情况下的进行放行
		for (String unUrl : unFilterURLs) {
			if (unUrl.endsWith("/*")) {
				unUrl = hreq.getContextPath() + unUrl.replace("/*", "");
				if (url.startsWith(unUrl)) {
					chain.doFilter(req, res);
					return;
				}
			} else if (url.startsWith(unUrl)) {
				chain.doFilter(req, res);
				return;
			}
		}
		Cookie cookies[] = hreq.getCookies();
		String ticket = this.getTicket(cookies);
		if (ticket == null && !url.contains(".")) {
			this.writeJsonData(hres);
			return;
		}
		if (ticket == null && url.contains(".jsp")) {
			hres.sendRedirect(hreq.getContextPath() + "/user-login-sys/unlogin");
//			hres.sendRedirect(hreq.getContextPath() + "/commons/jsp/error/unlogin.jsp");
			return;
		}
		// 对页面功能的控制实现
//		if (ticket != null) {
//			this.setExpire(ticket);
////			this.pageFunctionParams(hreq);
//		}
		chain.doFilter(req, res);
	}
	
	/**
	 * @description 根据用户的cookie，得到用户登陆的ticket数据，判断是否是合法登陆用户
	 * @author fengya
	 * @date 2017年5月24日 下午3:47:52
	 * @param cookies
	 * @return
	 * @throws 
	 * @return String
	 */
	private String getTicket(Cookie cookies[]){
		String ticket = null;
		if(cookies != null){
			for(Cookie ck: cookies){
				if(ck.getName().trim().equals("ticket")){
					ticket = ck.getValue();
					break;
				}
			}
		}
//		if (!StringUtil.isNullOrEmpty(ticket)) {
//			if (!EhRedisCache.USER_EH_REDIS_CACHE.getCache().exists(ticket)) {
//				ticket = null;
//			}
//		}
		return ticket;
	}

	/**
	 * @description 得到访问页面对应的功能对象
	 * @author fengya
	 * @date 2015-9-16 下午02:28:02
	 * @param hreq
	 * @return void
	 */
//	@SuppressWarnings("unchecked")
//	private void pageFunctionParams(HttpServletRequest hreq) {
//		String url = hreq.getRequestURI();
//		// 去除上下文
//		url = url.substring(hreq.getContextPath().length());
//		if (url.toLowerCase().contains(".jsp") || !url.contains(".")) {
//			Object roleObj = hreq.getSession().getAttribute("loginUserRole");
//			if (roleObj != null) {
//				List<Role> roleList = (List<Role>) roleObj;
//				Iterator<Role> roleIt = roleList.iterator();
//				List<PageFunction> functionParams = new ArrayList<PageFunction>();
//				List<PageFunction> funList = null;
//				while (roleIt.hasNext()) {
//					funList = InitCacheData.getInstance().getCacheTreeData(CacheType.ROLE_FUNCTION).get(roleIt.next().getId());
//					if (funList == null) {
//						return;
//					}
//					this.getPageFunctions(funList, functionParams, url);
//				}
//				if (!functionParams.isEmpty()) {
//					hreq.setAttribute("functions", functionParams);
//				}
//			}
//		}
//	}
//
//	/**
//	 * @description 根据URL路径判断是否是功能点对应的页面
//	 * @author fengya
//	 * @date 2015-9-16 下午02:28:39
//	 * @param funList
//	 * @param functionParams
//	 * @param url
//	 * @return void
//	 */
//	private void getPageFunctions(List<PageFunction> funList, List<PageFunction> functionParams, String url) {
//		Iterator<PageFunction> funIt = funList.iterator();
//		PageFunction fun = null;
//		while (funIt.hasNext()) {
//			fun = funIt.next();
//			if (url.startsWith(fun.getPageUrl())) {
//				functionParams.add(fun);
//			}
//		}
//	}

	/**
	 * @description 返回未登陆的数据到客户端
	 * @author fengya
	 * @date 2015-9-16 下午02:31:29
	 * @param hres
	 * @return void
	 */
	private void writeJsonData(HttpServletResponse hres) {
		PrintWriter pw = null;
		try {
			hres.setContentType("text/html;charset=utf-8");
			hres.setHeader("Pragma", "No-cache");
			hres.setHeader("Cache-Control", "no-cache");
			hres.setDateHeader("Expires", 0);
			pw = hres.getWriter();
			pw.write("unLogin");
			pw.flush();
		} catch (Exception e) {
			LOG.debug("输出流出现异常！",e);
		} finally {
			if (pw != null) {
				pw.close();
			}
		}
	}
}
